package com.wetao.flexiblerichtextview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.daquexian.flexiblerichtextview.FlexibleRichTextView;
import com.daquexian.flexiblerichtextview.FormatUtil;
import com.daquexian.flexiblerichtextview.MyConfige;
import com.pixplicity.sharp.Drawable2Bitmap;
import com.pixplicity.sharp.Sharp;
import com.pixplicity.sharp.SharpDrawable;
import com.wetao.flexiblerichtextview.bean.BoxData;
import com.wetao.flexiblerichtextview.bean.BoxData_2;


public class BoxDataActivity extends AppCompatActivity  implements View.OnClickListener, FlexibleRichTextView.OnFlexibleListener {

    private static final String TAG = "BoxDataActivity";
    private static final int HANDLER_FIRST_LOAD = 1;
    private static final int HANDLER_COMPLETE_DELEYED = 2;
    private static final int HANDLER_SHOW_SCROLL_VIEW = 3;
    private static final int HANDLER_SCROLL_BY = 4;

    private boolean isTurnNoneShow = false;  //是否在翻页的隐藏scrollView,然后显示出来（为了肉眼看不出滚动效果，和尝试处理残影）
    private boolean isTurnPage = true;  //是翻页显示还是滚动显示
    private LinearLayout lyt_page_bottom;
    private Button btn_page_prev;
    private Button btn_page_next;
    private TextView tv_page_num;
    private int currentPage = 0;
    private int totalPage = 0;
    private int totalHeight = 0;
    private int currentHeight = 0;
    private ScrollView sv_question;
    int questionIndex;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_FIRST_LOAD:{
                    //TextView tv_html_1 = (TextView) findViewById(R.id.tv_html_1);
                    //HtmlTextView html_text = (HtmlTextView) findViewById(R.id.html_text);
                    FlexibleRichTextView.load_time = System.currentTimeMillis();
                    if(questionIndex == 0) {
                        //testTag(); //测试单个标签
                    } else if(questionIndex == 1) {
                        //testJson_1(); //测试张一鸣给的json数据文档
                    } else {
                        testJson_2("json_" + questionIndex + ".json"); //从后台管理系统获得各种文档测试
                    }

                    //tv_html_1.setText(Html.fromHtml("<table><tr><td>1</td><td>2</td></tr></table>"));
                    /* html_text.setHtml("<table><tr><td>1</td><td>2</td></tr></table>",
                       new HtmlResImageGetter(html_text));*/
                    //html_text.setHtml("<p>11111</p><span>222</span><span>333</span>");
                }break;
                case HANDLER_COMPLETE_DELEYED:{
                    //Log.i(TAG, "------------------------>>>>>>>>>10");
                    currentHeight = sv_question.getHeight();
                    totalHeight = sv_question.getChildAt(0).getHeight();
                    if(totalHeight > currentHeight) {
                        lyt_page_bottom.setVisibility(View.VISIBLE);
                        float f_totalPage = totalHeight/(currentHeight * MyConfige.scroll_by_page_percent);
                        int floor_totalPage = (int)(Math.floor(f_totalPage));
                        if((f_totalPage - floor_totalPage) * (currentHeight * MyConfige.scroll_by_page_percent) > (currentHeight * (1 - MyConfige.scroll_by_page_percent))) {
                            totalPage = floor_totalPage + 1;
                        } else {
                            totalPage = floor_totalPage;
                        }

                        Log.e(TAG, "滚动高度：h1 = " + currentHeight + ", h2 = " + totalHeight + ", f_totalPage = " + f_totalPage + ", totalPage = " + totalPage);
                        refreshPageView();
                    }

                }break;
                case HANDLER_SHOW_SCROLL_VIEW:{
                    sv_question.setVisibility(View.VISIBLE);
                }break;
                case HANDLER_SCROLL_BY:{
                    int by = msg.arg1;
                    sv_question.scrollBy(0, by);
                    refreshPageView();
                    handler.sendEmptyMessageDelayed(HANDLER_SHOW_SCROLL_VIEW, 100);
                }break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_box_data);
        Intent intent = getIntent();
        questionIndex = intent.getIntExtra("questionIndex", 0);
        isTurnPage = intent.getBooleanExtra("isTurnPage", true);

        //禁止上下滚动
        sv_question = (ScrollView)findViewById(R.id.sv_question);
        if(isTurnPage) {
            sv_question.setOnTouchListener(new View.OnTouchListener(){
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    return true;
                }
            });
        }

        lyt_page_bottom = (LinearLayout)findViewById(R.id.lyt_page_bottom);
        btn_page_prev = (Button) findViewById(R.id.btn_page_prev);
        btn_page_next = (Button) findViewById(R.id.btn_page_next);
        tv_page_num = (TextView) findViewById(R.id.tv_page_num);

        btn_page_prev.setOnClickListener(this);
        btn_page_next.setOnClickListener(this);


        //必须延时一点时间再加载数据，原因是html解析需要一点时间，所以要界面先显示再加载。
        handler.sendEmptyMessageDelayed(HANDLER_FIRST_LOAD, 50);

        ImageView iv_sharp = (ImageView)findViewById(R.id.iv_sharp);
        TextView tv_sharp = (TextView)findViewById(R.id.tv_sharp);
        Sharp.loadString("<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:wrs=\"http://www.wiris.com/xml/cvs-extension\" height=\"24\" width=\"85\" wrs:baseline=\"19\"><!--MathML: <math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\" mathvariant=\"italic\"><mo>[</mo><mo>-</mo><mn>5</mn><msqrt><mn>2</mn></msqrt><mtext>&#xFF0C;1</mtext><mo>]</mo></math>--><defs><style type=\"text/css\">@font-face{font-family:'math1da40657c9fece7e48d30af42d3';src:url(data:font/truetype;charset=utf-8;base64,AAEAAAAMAIAAAwBAT1MvMi7iBBMAAADMAAAATmNtYXDEvmKUAAABHAAAADRjdnQgDVUNBwAAAVAAAAA6Z2x5ZoPi2VsAAAGMAAAAcmhlYWQQC2qxAAACAAAAADZoaGVhCGsXSAAAAjgAAAAkaG10eE2rRkcAAAJcAAAACGxvY2EAHTwYAAACZAAAAAxtYXhwBT0FPgAAAnAAAAAgbmFtZaBxlY4AAAKQAAABn3Bvc3QB9wD6AAAEMAAAACBwcmVwa1uragAABFAAAAAUAAADS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AaABzACAARgBvAHIAIABNAG8AcgBlAAADAAAAAAAAAfQA+gAAAAAAAAAAAAAAAAAAAAAAAAAAuQcRAACNhRgAsgAAABUUE7EAAT8=)format('truetype');font-weight:normal;font-style:normal;}</style></defs><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"2.5\" y=\"19\">[</text><text font-family=\"math1da40657c9fece7e48d30af42d3\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"11.5\" y=\"19\">&#x2212;</text><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"23.5\" y=\"19\">5</text><polyline fill=\"none\" points=\"12,-16 11,-16 5,0 2,-6\" stroke=\"#000000\" stroke-linecap=\"square\" stroke-width=\"1\" transform=\"translate(28.5,20.5)\"/><polyline fill=\"none\" points=\"5,0 2,-6 0,-5\" stroke=\"#000000\" stroke-linecap=\"square\" stroke-width=\"1\" transform=\"translate(28.5,20.5)\"/><line stroke=\"#000000\" stroke-linecap=\"square\" stroke-width=\"1\" x1=\"40.5\" x2=\"53.5\" y1=\"4.5\" y2=\"4.5\"/><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"46.5\" y=\"19\">2</text><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"66.5\" y=\"19\">&#xFF0C;1</text><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"81.5\" y=\"19\">]</text></svg>").into(iv_sharp);
        SharpDrawable sharpDrawable = Sharp.loadString("<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:wrs=\"http://www.wiris.com/xml/cvs-extension\" height=\"24\" width=\"85\" wrs:baseline=\"19\"><!--MathML: <math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\" mathvariant=\"italic\"><mo>[</mo><mo>-</mo><mn>5</mn><msqrt><mn>2</mn></msqrt><mtext>&#xFF0C;1</mtext><mo>]</mo></math>--><defs><style type=\"text/css\">@font-face{font-family:'math1da40657c9fece7e48d30af42d3';src:url(data:font/truetype;charset=utf-8;base64,AAEAAAAMAIAAAwBAT1MvMi7iBBMAAADMAAAATmNtYXDEvmKUAAABHAAAADRjdnQgDVUNBwAAAVAAAAA6Z2x5ZoPi2VsAAAGMAAAAcmhlYWQQC2qxAAACAAAAADZoaGVhCGsXSAAAAjgAAAAkaG10eE2rRkcAAAJcAAAACGxvY2EAHTwYAAACZAAAAAxtYXhwBT0FPgAAAnAAAAAgbmFtZaBxlY4AAAKQAAABn3Bvc3QB9wD6AAAEMAAAACBwcmVwa1uragAABFAAAAAUAAADSwGQAAUAAAQABAAAAAAABAAEAAAAAAAAAQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAgICAAAAAg1UADev96AAAD6ACWAAAAAAACAAEAAQAAABQAAwABAAAAFAAEACAAAAAEAAQAAQAAIhL//wAAIhL//93vAAEAAAAAAAABVAMsAIABAABWACoCWAIeAQ4BLAIsAFoBgAKAAKAA1ACAAAAAAAAAACsAVQCAAKsA1QEAASsABwAAAAIAVQAAAwADqwADAAcAADMRIRElIREhVQKr/asCAP4AA6v8VVUDAAABAIABVQLVAasAAwAwGAGwBBCxAAP2sAM8sQIH9bABPLEFA+YAsQAAExCxAAblsQABExCwATyxAwX1sAI8EyEVIYACVf2rAatWAAAAAQAAAAEAANV4zkFfDzz1AAMEAP/////WOhNz/////9Y6E3MAAP8gBIADqwAAAAoAAgABAAAAAAABAAAD6P9qAAAXcAAA/7YEgAABAAAAAAAAAAAAAAAAAAAAAgNSAFUDVgCAAAAAAAAAACgAAAByAAEAAAACAF4ABQAAAAAAAgCABAAAAAAABAAA3gAAAAAAAAAVAQIAAAAAAAAAAQASAAAAAAAAAAAAAgAOABIAAAAAAAAAAwAwACAAAAAAAAAABAASAFAAAAAAAAAABQAWAGIAAAAAAAAABgAJAHgAAAAAAAAACAAcAIEAAQAAAAAAAQASAAAAAQAAAAAAAgAOABIAAQAAAAAAAwAwACAAAQAAAAAABAASAFAAAQAAAAAABQAWAGIAAQAAAAAABgAJAHgAAQAAAAAACAAcAIEAAwABBAkAAQASAAAAAwABBAkAAgAOABIAAwABBAkAAwAwACAAAwABBAkABAASAFAAAwABBAkABQAWAGIAAwABBAkABgAJAHgAAwABBAkACAAcAIEATQBhAHQAaAAgAEYAbwBuAHQAUgBlAGcAdQBsAGEAcgBNAGEAdABoAHMAIABGAG8AcgAgAE0AbwByAGUAIABNAGEAdABoACAARgBvAG4AdABNAGEAdABoACAARgBvAG4AdABWAGUAcgBzAGkAbwBuACAAMQAuADBNYXRoX0ZvbnQATQBhAHQAaABzACAARgBvAHIAIABNAG8AcgBlAAADAAAAAAAAAfQA+gAAAAAAAAAAAAAAAAAAAAAAAAAAuQcRAACNhRgAsgAAABUUE7EAAT8=)format('truetype');font-weight:normal;font-style:normal;}</style></defs><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"2.5\" y=\"19\">[</text><text font-family=\"math1da40657c9fece7e48d30af42d3\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"11.5\" y=\"19\">&#x2212;</text><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"23.5\" y=\"19\">5</text><polyline fill=\"none\" points=\"12,-16 11,-16 5,0 2,-6\" stroke=\"#000000\" stroke-linecap=\"square\" stroke-width=\"1\" transform=\"translate(28.5,20.5)\"/><polyline fill=\"none\" points=\"5,0 2,-6 0,-5\" stroke=\"#000000\" stroke-linecap=\"square\" stroke-width=\"1\" transform=\"translate(28.5,20.5)\"/><line stroke=\"#000000\" stroke-linecap=\"square\" stroke-width=\"1\" x1=\"40.5\" x2=\"53.5\" y1=\"4.5\" y2=\"4.5\"/><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"46.5\" y=\"19\">2</text><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"66.5\" y=\"19\">&#xFF0C;1</text><text font-family=\"Arial\" font-size=\"16\" font-style=\"italic\" text-anchor=\"middle\" x=\"81.5\" y=\"19\">]</text></svg>").getDrawable();
        //Sharp.loadResource(getResources(), R.raw.my).into(iv_sharp);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append("112233");
        Bitmap decodedByte = Drawable2Bitmap.DrawableToBitmap(sharpDrawable);
        spannableStringBuilder.setSpan(new ImageSpan(this, decodedByte, ImageSpan.ALIGN_BASELINE), 2, 3, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv_sharp.setText(spannableStringBuilder);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_page_prev:{
                currentPage--;
                if(isTurnNoneShow) {
                    sv_question.setVisibility(View.INVISIBLE);
                    Message msg = handler.obtainMessage();
                    msg.what = HANDLER_SCROLL_BY;
                    msg.arg1 = -(int) (currentHeight * MyConfige.scroll_by_page_percent);
                    handler.sendMessageDelayed(msg, 50);
                    //handler.sendEmptyMessageDelayed(HANDLER_SHOW_SCROLL_VIEW, 100);
                } else {
                    sv_question.scrollBy(0, -(int)(currentHeight * MyConfige.scroll_by_page_percent));
                    refreshPageView();
                }


            }break;
            case R.id.btn_page_next:{
                currentPage++;
                if(isTurnNoneShow) {
                    sv_question.setVisibility(View.INVISIBLE);
                    Message msg = handler.obtainMessage();
                    msg.what = HANDLER_SCROLL_BY;
                    msg.arg1 = (int) (currentHeight * MyConfige.scroll_by_page_percent);
                    handler.sendMessageDelayed(msg, 100);
                    //handler.sendEmptyMessageDelayed(HANDLER_SHOW_SCROLL_VIEW, 100);
                } else {
                    sv_question.scrollBy(0, (int)(currentHeight * MyConfige.scroll_by_page_percent));
                    refreshPageView();
                }

            }break;
        }
    }

    @Override
    public void onComplete(FlexibleRichTextView view) {
        Log.i(TAG, "数据全部加载完成");
        int h1 = sv_question.getHeight();
        int h2 = sv_question.getChildAt(0).getHeight();
        Log.e(TAG, "滚动高度：h1 = " + h1 + ", h2 = " + h2);
        //Log.i(TAG, "------------------------>>>>>>>>>8");
        if(h2 > h1 && isTurnPage) {
            //Log.i(TAG, "------------------------>>>>>>>>>7");
            /*lyt_page_bottom.setVisibility(View.VISIBLE);
            refreshPageView();*/
            handler.sendEmptyMessageDelayed(HANDLER_COMPLETE_DELEYED, 50);
        }

    }

    private void refreshPageView() {
        tv_page_num.setText((currentPage + 1) + "/" + (totalPage == 0 ? 1 : totalPage));
        btn_page_prev.setClickable(false);
        btn_page_next.setClickable(false);
        btn_page_prev.setTextColor(Color.parseColor("#cccccc"));
        btn_page_next.setTextColor(Color.parseColor("#cccccc"));
        if(currentPage > 0) {
            btn_page_prev.setClickable(true);
            btn_page_prev.setTextColor(Color.parseColor("#000000"));
        }
        if((totalPage - 1) > currentPage){
            btn_page_next.setClickable(true);
            btn_page_next.setTextColor(Color.parseColor("#000000"));
        }
    }

    private void testJson_2(String fileName) {
        FlexibleRichTextView flexibleRichTextView = (FlexibleRichTextView) findViewById(R.id.frtv);
        flexibleRichTextView.setOnFlexibleListenerr(this);
        BoxData res = null;
        String json = TestJson.getJson(this, fileName);
        if(JsonUtils.isGoodJson(json)) {
            res = JsonUtils.fromJson(json, BoxData.class);
        }
        StringBuilder stringBuilder = new StringBuilder();
        if(res != null) {

            for(BoxData_2 boxData_2 : res.getData().getQuestionList()) {
                stringBuilder.append(FormatUtil.format_questionNo(boxData_2.getQuestionNo().toString()));
                stringBuilder.append(FormatUtil.format_question(boxData_2.getQuestion()));
                if(boxData_2.getOptions() != null && boxData_2.getOptions().size() > 0) {
                    for(int i = 0; i <  boxData_2.getOptions().size(); i++) {
                        stringBuilder.append(FormatUtil.format_option(i, boxData_2.getOptions().get(i)));
                    }
                }

                if(boxData_2.getAnswers() != null && boxData_2.getAnswers().size() > 0) {
                    for(int i = 0; i <  boxData_2.getAnswers().size(); i++) {
                        stringBuilder.append(FormatUtil.format_answers(i, boxData_2.getAnswers().get(i), boxData_2.getAnswers().size()));
                    }
                } else {
                    stringBuilder.append(FormatUtil.format_answers(0, "", 1));
                }

                stringBuilder.append(FormatUtil.format_explain(boxData_2.getExplain()));
            }
        }
        flexibleRichTextView.setText(stringBuilder.toString());
    }
}
